package com.ynet.middleground.approve.listener.user;

import java.util.Optional;

import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.impl.persistence.entity.VariableInstance;
import org.springframework.context.annotation.DependsOn;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Throwables;
import com.ynet.core.exception.BusinessException;
import com.ynet.core.log.IfpLogger;
import com.ynet.middleground.approve.cmd.SpringContextUtils;
import com.ynet.middleground.approve.listener.BaseListener;
import com.ynet.middleground.approve.model.UserCenterModel;
import com.ynet.middleground.user.bean.ChangeUserInfoReq;

/**
 * @author liulx
 * @description 调用用户中心-修改用户信息服务
 * @date 2019-12-03 09:11
 */
@DependsOn("springContextUtils")
public class UpdateUserInfoListener extends BaseListener implements ExecutionListener {

    private UserCenterModel userCenterModel = SpringContextUtils.getBean(UserCenterModel.class);

    /**
     * 修改用户信息变量key
     */
    private static String changeUserInfoReqKey = "changeUserInfoReq";

    @Override
    public void notify(DelegateExecution delegateExecution) {
        String startUserId = getStartUserId(delegateExecution);
        String channel = getChannel(delegateExecution);
        String operationUserId = getOperationUserId(delegateExecution);
        VariableInstance variableInstance = delegateExecution.getVariableInstance(changeUserInfoReqKey);
        Optional.ofNullable(variableInstance).orElseThrow(() -> new BusinessException("获取修改用户信息对象变量为空", "ECAP0500"));
        ChangeUserInfoReq changeUserInfoReq;
        if (variableInstance.getValue() instanceof ChangeUserInfoReq) {
            changeUserInfoReq = (ChangeUserInfoReq)variableInstance.getValue();
        } else {
            try {
                changeUserInfoReq = JSONObject.parseObject(JSONObject.toJSONString(variableInstance.getValue()),
                    ChangeUserInfoReq.class);
            } catch (Exception e) {
                IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "修改用户信息转换异常, case:{}",
                    Throwables.getStackTraceAsString(e));
                throw new BusinessException("修改用户信息格式有误", "ECAP0501");
            }
        }
        userCenterModel.updateUserInfo(startUserId, channel, operationUserId, changeUserInfoReq);
    }

}
